import paho.mqtt.client as mqtt
import threading

import queue

class MQTTClient:
    def __init__(self, broker_address, broker_port=1883):
        self.client = mqtt.Client()
        self.broker_address = broker_address
        self.broker_port = broker_port
        self.connected = False

        # Setup callbacks
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_message=self.on_message
        self.message_queue = queue.Queue()

    def connect(self):
        self.client.connect(self.broker_address, self.broker_port)
        self.client.loop_start()  # Start MQTT client loop

    def disconnect(self):
        self.client.disconnect()
        self.client.loop_stop()
        self.connected = False

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            self.connected = True
            print(f"Connected to MQTT broker at {self.broker_address}:{self.broker_port}")
        else:
            print(f"Failed to connect to MQTT broker with code {rc}")     

    def on_disconnect(self, client, userdata, rc):
        self.connected = False
        print("Disconnected from MQTT broker")

    def subscribe(self, topic):
        self.client.subscribe(topic)

    def publish(self, topic, message):
        self.client.publish(topic, message)
        
    def on_message(self, client, userdata, message):
        payload = message.payload.decode()
        #print(f"Received message '{payload}' on topic '{message.topic}'")
        self.message_queue.put((message.topic, payload))  # Store message in queue 
        
    def get_message(self):
        #Retrieve a message from the queue.
        try:
            return self.message_queue.get_nowait()
        except queue.Empty:
            return None

